import qs from 'qs'
import axios from 'axios'
import { message } from '@/hooks'
import router from '../router'
import { getToken, removeToken } from '@/utils/auth'

// 定义请求前缀
axios.defaults.baseURL = process.env.VUE_APP_BASE_API
axios.defaults.timeout = 60000
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
axios.interceptors.request.use(
  config => {
    config.headers.Authorization = getToken() ?? ''
    config.headers.Accesstoken = getToken() ?? ''
    return config
  },
  error => {
    return Promise.error(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    console.log('response', response)
    if (response.status !== 200) {
      return Promise.reject(response)
    }
    return response
  },
  error => {
    const { response } = error
    // console.log("异常处理",response)
    httpErrorStatusHandle(response)
    return Promise.reject(response)
  }
)

export default {
  /**
   * get方法对应GET请求
   * @param {*} url
   * @param {*} params
   * @returns
   */
  get: (url, params) => {
    return new Promise((resolve, reject) => {
      axios
        .get(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  /**
   * post方法对应POST请求
   * @param {*} url
   * @param {*} params
   * @returns
   */
  postJson: (url, params) => {
    return new Promise((resolve, reject) => {
      axios
        .post(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  /**
   * post方法对应POST请求 (请求参数转为formData格式)
   * @param {*} url
   * @param {*} params
   * @returns
   */
  post: (url, params) => {
    return new Promise((resolve, reject) => {
      axios
        .post(url, params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          transformRequest: [
            params => {
              return qs.stringify(params)
            }
          ]
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  /**
   * delete方法对应DELETE请求
   * @param {*} url
   * @param {*} params
   * @returns
   */
  delete: (url, params) => {
    return new Promise((resolve, reject) => {
      axios
        .delete(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  /**
   * put方法对应PUT请求
   * @param {*} url
   * @param {*} params
   * @returns
   */
  put: (url, params) => {
    return new Promise((resolve, reject) => {
      axios
        .put(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  /**
   * patch对应PATCH请求
   * @param {*} url
   * @param {*} params
   * @returns
   */
  patch: (url, params) => {
    return new Promise((resolve, reject) => {
      axios
        .patch(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

// 未登录带参数重定向
function redirectToLogin() {
  router
    .replace({
      path: '/login',
      query: {
        redirect: router.currentRoute.fullPath
      }
    })
    .catch(() => {})
}

// 系统正在维护
function redirectToPreserve() {
  router
    .replace({
      path: '/410'
    })
    .catch(() => {})
}

/**
 * @description 错误请求统一处理
 * @param {*} error
 * @returns
 */
function httpErrorStatusHandle(error) {
  const {
    data: { msg },
    config
  } = error
  const status = error.status
  // 处理被取消的请求
  if (axios.isCancel(error)) return console.error('请求的重复请求：' + msg)
  let messages = ''

  console.log(error, status)
  if (error && status) {
    switch (status) {
      case 302:
        messages = '接口重定向了！'
        break
      case 400:
        messages = '参数不正确！'
        break
      case 401:
        messages = '您未登录，或者登录已经超时，请先登录！'
        removeToken()
        redirectToLogin()
        break
      case 403:
        messages = '系统正在维护中！'
        redirectToPreserve()
        break
      case 404:
        messages = `请求地址出错: ${config.url}`
        break
      case 408:
        messages = '请求超时！'
        break
      case 409:
        messages = '系统已存在相同数据！'
        break
      case 500:
        messages = msg
        break
      case 501:
        messages = '服务未实现！'
        break
      case 502:
        messages = '网关错误！'
        break
      case 503:
        messages = '服务不可用！'
        break
      case 504:
        messages = '服务暂时无法访问，请稍后再试！'
        break
      case 505:
        messages = 'HTTP版本不受支持！'
        break
      default:
        messages = '异常问题，请联系管理员！'
        break
    }
  }
  if (msg.includes('timeout')) messages = '网络请求超时！'
  if (msg.includes('Network')) messages = window.navigator.onLine ? '服务端异常！' : '您断网了！'
  message.error({
    message: messages
  })
  return false
}
